/* eslint-disable radix */
/* eslint-disable no-use-before-define */
/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { computed, defineComponent, SetupContext, ref, withModifiers, watch, onMounted } from 'vue';
import { useResizeObserver } from '@vueuse/core';
import { WeatherProps, weatherProps } from './weather.props';
import './weather.css';
import FProgress from '../../progress/src/progress.component';
import * as echarts from 'echarts';
import jsonp from 'jsonp';
import CryptoJS from 'crypto-js';

export default defineComponent({
    name: 'FWeather',
    components: {
        "f-progress": FProgress
    },
    props: weatherProps,
    emits: [] as (string[] & ThisType<void>) | undefined,
    setup(props: WeatherProps, context: SetupContext) {
        const elementRef = ref();        
        // 城市列表
        const cityItems = [
            { "province": "北京", "city": ["北京"]},
            { "province": "山东", "city": ["济南", "青岛"]},
            { "province": "黑龙江", "city": ["牡丹江", "齐齐哈尔"]},
        ];
        // 主题列表
        const themeItems = [
            {title: "school", adviceItems: ["clothes", "sports", "sunscreen"]},
            {title: "office", adviceItems: ["clothes", "traffic", "umbrella"]},
            {title: "construction", adviceItems: ["clothes", "chill", "heatstroke"]},
            {title: "tourism", adviceItems: ["clothes", "sunscreen", "tourism"]},
        ]

        // 主题参数
        const theme = ref(1);

        // 天气实况（api）
        const temperature = ref(15);
        const max = ref(24);
        const min = ref(15);
        const weather = ref("晴");
        const air = ref(500);
        const sunriseTime = ref(new Date(2024,3,16,22,0,0,0));
        const sunsetTime = ref(new Date(2024,3,16,23,0,0,0));
        const adviceItems = [
            {key: "clothes", value: { name: "穿衣", info: "毛衣", detail: "建议穿长袖毛衣等服装。"}},
            {key: "sports", value: { name: "运动", info: "适宜", detail: "各项气象条件都很好，很适合户外运动。"}},
            {key: "sunscreen", value: { name: "防晒", info: "强", detail: "建议涂抹SPF在15-20之间，PA++的防晒护肤品。"}},
            {key: "traffic", value: { name: "交通", info: "良好", detail: "天气较好，路面干燥，交通气象条件良好，车辆可以正常行驶。"}},
            {key: "umbrella", value: { name: "雨伞", info: "不带伞", detail: "天气较好，您在出门的时候无须带雨伞。"}},
            {key: "chill", value: { name: "风寒", info: "无", detail: "温度未达到风寒所需的低温，稍作防寒准备即可。"}},
            {key: "heatstroke", value: { name: "中暑", info: "无中暑风险", detail: "天气不热，在炎炎夏日中十分难得，可以告别暑气漫漫啦~"}},
            {key: "tourism", value: { name: "旅游", info: "适宜", detail: "天气较好，温度适宜，是个好天气哦。这样的天气适宜旅游，您可以尽情地享受大自然的风光。"}},
        ];
        const proindexItemsSet = [[
            { title: "紫外线", icon: "UV", value: "中等", info: "16:00前注意防晒", explain: "紫外线指数（UVI）测量紫外线辐射。UVI越高，潜在伤害就越大，造成伤害的速度也越快。"},
            { title: "降水量", icon: "rainfall", value: "0mm", info: "过去24小时", explain: "降水量，是指12或24小时内降雨（雪）量的总和。"},            
        ], [
            { title: "湿度", icon: "humidity", value: "31%", info: "露点温度为4°", explain: "空气中含水量与空气可容纳水量的比值。气温越高，空气可容纳的水量就越多。湿度高意味着可能结露或起雾。"},
            { title: "体感温度", icon: "apparentTemp", value: "14°", info: "风较大，体感更凉", explain: "体感温度传达身体感觉有多暖或多冷，可能与实际温度不同。体感温度受湿度和风影响。"},            
        ], [
            { title: "气压", icon: "pressure", value: "1010mpa", info: "当前气压较稳定", explain: "气压的显著急剧变化用于预测天气变化。例如，气压降低表示雨雪即将来临，升高则表示天气将好转。"},
            { title: "能见度", icon: "visibility", value: "19km", info: "目前非常好", explain: "能见度会告诉你可以清晰地看到多远以外的物体。能见度测量大气透明度，不考虑光照强度或障碍物。"},            
        ]];
        const dayItemsSet = [[
            { icon: "sunny", temp: 15 },
            { icon: "sunny", temp: 16 },
            { icon: "sunny", temp: 20 },
            { icon: "sunny", temp: 22 },
            { icon: "sunny", temp: 24 },
            { icon: "cloudy", temp: 23 },
            { icon: "cloudy", temp: 20 },
            { icon: "cloudy", temp: 19 },
            { icon: "cloudy", temp: 19 },
            { icon: "cloudy", temp: 18 },
            { icon: "rainy1", temp: 18 },
            { icon: "rainy1", temp: 17 },
            { icon: "rainy1", temp: 15 },
            { icon: "rainy1", temp: 15 },
            { icon: "rainy2", temp: 15 },
            { icon: "rainy2", temp: 15 },
            { icon: "rainy2", temp: 15 },
            { icon: "sunny", temp: 15 },
            { icon: "sunny", temp: 15 },
            { icon: "sunny", temp: 18 },
            { icon: "sunny", temp: 19 },
            { icon: "sunny", temp: 19 },
            { icon: "sunny", temp: 20 },
            { icon: "sunny", temp: 20 }
        ],[
            { icon: "rainy2", temp: 15 },
            { icon: "rainy2", temp: 15 },
            { icon: "rainy2", temp: 15 },
            { icon: "sunny", temp: 15 },
            { icon: "sunny", temp: 15 },
            { icon: "sunny", temp: 18 },
            { icon: "sunny", temp: 19 },
            { icon: "sunny", temp: 19 },
            { icon: "sunny", temp: 20 },
            { icon: "sunny", temp: 20 }, 
            { icon: "rainy2", temp: 21 },
            { icon: "rainy2", temp: 21 },
            { icon: "rainy2", temp: 21 },
            { icon: "sunny", temp: 21 },
            { icon: "sunny", temp: 22 },
            { icon: "sunny", temp: 24 },
            { icon: "sunny", temp: 24 },
            { icon: "sunny", temp: 23 },
            { icon: "sunny", temp: 20 },
            { icon: "sunny", temp: 20 }, 
            { icon: "sunny", temp: 19 },
            { icon: "sunny", temp: 19 },
            { icon: "sunny", temp: 15 },
            { icon: "sunny", temp: 15 },
        ],
        // [
        //     { icon: "foggy", temp: 11 },
        //     { icon: "foggy", temp: 12 },
        //     { icon: "foggy", temp: 14 },
        //     { icon: "foggy", temp: 15 },
        //     { icon: "foggy", temp: 17 },
        //     { icon: "foggy", temp: 18 },
        //     { icon: "foggy", temp: 19 },
        //     { icon: "foggy", temp: 19 },
        //     { icon: "foggy", temp: 20 },
        //     { icon: "foggy", temp: 20 }, 
        //     { icon: "foggy", temp: 21 },
        //     { icon: "foggy", temp: 21 },
        //     { icon: "foggy", temp: 21 },
        //     { icon: "foggy", temp: 21 },
        //     { icon: "sunny", temp: 22 },
        //     { icon: "sunny", temp: 26 },
        //     { icon: "sunny", temp: 26 },
        //     { icon: "sunny", temp: 25 },
        //     { icon: "sunny", temp: 20 },
        //     { icon: "sunny", temp: 20 }, 
        //     { icon: "foggy", temp: 19 },
        //     { icon: "foggy", temp: 19 },
        //     { icon: "foggy", temp: 15 },
        //     { icon: "foggy", temp: 15 },            
        // ],[
        //     { icon: "cloudy", temp: 7 },
        //     { icon: "cloudy", temp: 8 },
        //     { icon: "cloudy", temp: 10 },
        //     { icon: "sunny", temp: 10 },
        //     { icon: "sunny", temp: 14 },
        //     { icon: "cloudy", temp: 18 },
        //     { icon: "cloudy", temp: 19 },
        //     { icon: "cloudy", temp: 19 },
        //     { icon: "sunny", temp: 20 },
        //     { icon: "sunny", temp: 20 }, 
        //     { icon: "cloudy", temp: 21 },
        //     { icon: "cloudy", temp: 21 },
        //     { icon: "cloudy", temp: 21 },
        //     { icon: "cloudy", temp: 21 },
        //     { icon: "cloudy", temp: 22 },
        //     { icon: "cloudy", temp: 22 },
        //     { icon: "sunny", temp: 21 },
        //     { icon: "sunny", temp: 21 },
        //     { icon: "sunny", temp: 20 },
        //     { icon: "sunny", temp: 20 }, 
        //     { icon: "sunny", temp: 19 },
        //     { icon: "sunny", temp: 19 },
        //     { icon: "sunny", temp: 15 },
        //     { icon: "sunny", temp: 15 },            
        // ],[
        //     { icon: "snowy1", temp: 3 },
        //     { icon: "snowy1", temp: 3 },
        //     { icon: "snowy1", temp: 3 },
        //     { icon: "snowy1", temp: 4 },
        //     { icon: "sunny", temp: 4 },
        //     { icon: "sunny", temp: 4 },
        //     { icon: "sunny", temp: 5 },
        //     { icon: "sunny", temp: 6 },
        //     { icon: "sunny", temp: 8 },
        //     { icon: "sunny", temp: 8 }, 
        //     { icon: "snowy1", temp: 10 },
        //     { icon: "snowy1", temp: 10 },
        //     { icon: "snowy1", temp: 10 },
        //     { icon: "snowy1", temp: 10 },
        //     { icon: "snowy1", temp: 10 },
        //     { icon: "snowy1", temp: 9 },
        //     { icon: "sunny", temp: 9 },
        //     { icon: "sunny", temp: 9 },
        //     { icon: "sunny", temp: 9 },
        //     { icon: "sunny", temp: 9 }, 
        //     { icon: "sunny", temp: 7 },
        //     { icon: "sunny", temp: 7 },
        //     { icon: "sunny", temp: 7 },
        //     { icon: "sunny", temp: 5 },            
        // ],[
        //     { icon: "sunny", temp: 5 },
        //     { icon: "sunny", temp: 7 },
        //     { icon: "sunny", temp: 7 },
        //     { icon: "sunny", temp: 7 },
        //     { icon: "sunny", temp: 7 },
        //     { icon: "sunny", temp: 7 },
        //     { icon: "sunny", temp: 10 },
        //     { icon: "sunny", temp: 10 },
        //     { icon: "sunny", temp: 10 },
        //     { icon: "sunny", temp: 15 }, 
        //     { icon: "sunny", temp: 15 },
        //     { icon: "sunny", temp: 15 },
        //     { icon: "sunny", temp: 16 },
        //     { icon: "sunny", temp: 19 },
        //     { icon: "sunny", temp: 19 },
        //     { icon: "sunny", temp: 19 },
        //     { icon: "sunny", temp: 19 },
        //     { icon: "sunny", temp: 18 },
        //     { icon: "sunny", temp: 17 },
        //     { icon: "sunny", temp: 17 }, 
        //     { icon: "sunny", temp: 17 },
        //     { icon: "sunny", temp: 17 },
        //     { icon: "sunny", temp: 16 },
        //     { icon: "sunny", temp: 10 },            
        // ],[
        //     { icon: "snowy2", temp: 4 },
        //     { icon: "snowy2", temp: 4 },
        //     { icon: "snowy2", temp: 4 },
        //     { icon: "sunny", temp: 4 },
        //     { icon: "sunny", temp: 4 },
        //     { icon: "sunny", temp: 6 },
        //     { icon: "sunny", temp: 6 },
        //     { icon: "sunny", temp: 6 },
        //     { icon: "sunny", temp: 7 },
        //     { icon: "sunny", temp: 8 }, 
        //     { icon: "snowy2", temp: 8 },
        //     { icon: "snowy2", temp: 8 },
        //     { icon: "snowy2", temp: 8 },
        //     { icon: "sunny", temp: 8 },
        //     { icon: "sunny", temp: 10 },
        //     { icon: "sunny", temp: 10 },
        //     { icon: "sunny", temp: 9 },
        //     { icon: "sunny", temp: 9 },
        //     { icon: "sunny", temp: 10 },
        //     { icon: "sunny", temp: 10 }, 
        //     { icon: "sunny", temp: 8 },
        //     { icon: "sunny", temp: 7 },
        //     { icon: "sunny", temp: 7 },
        //     { icon: "sunny", temp: 7 },            
        // ]
        ];
        const weekItems = [
            { icon: "rainy1", max: 24, min: 15 },
            { icon: "rainy2", max: 24, min: 15 },
            { icon: "foggy",  max: 26, min: 11 },
            { icon: "cloudy", max: 22, min: 7 },
            { icon: "snowy1", max: 10, min: 3 },
            { icon: "sunny", max: 19, min: 5 },
            { icon: "snowy2", max: 10, min: 4 }
        ];

        // 是否显示城市选择
        const isShowSelectCity = ref(false);
        // 是否显示详细信息
        const isShowDetail = ref(false);
        // 是否显示天气预报
        const isShowReport = ref(true);
        // 下拉菜单中选中的省份
        const selectedProvinceId = ref(0);
        // 当前选中的省份
        const currentProvinceId = ref(0);
        // 当前选中的城市
        const currentCityId = ref(0);
        // 当前选中的日期
        const currentDayId = ref(0);
            
        // 图表对象
        const chartSunset = ref<echarts.EChartsType>();
        const chart24h = ref<echarts.EChartsType>();
        const chart7d = ref<echarts.EChartsType>();

        // 空气质量等级
        const airLevel = computed(() => {
            if(air.value <= 50)
                return "优";
            else if(air.value <= 100)
                return "良"
            else if(air.value <= 150)
                return "轻度污染";
            else if(air.value <= 200)
                return "中度污染";
            else if(air.value <= 300)
                return "重度污染";
            else
                return "严重污染";
        });
        
        // 预警信息
        const warning = computed(() => {
            // 是否雾霾
            if(air.value > 300)
                return {type:"smog", color: "red", title: "雾霾红色预警"};
            else if(air.value > 200)
                return {type:"smog", color: "orange", title: "雾霾橙色预警"};
            else if(air.value > 150)
                return {type:"smog", color: "yellow", title: "雾霾黄色预警"};
            // 是否高温
            if(Math.max(...dayItemsSet[0].map(v => {return v.temp})) > 40)
                return {type:"highTemp", color: "red", title: "高温红色预警"};
            else if(Math.max(...dayItemsSet[0].map(v => {return v.temp})) > 37)
                return {type:"highTemp", color: "orange", title: "高温橙色预警"};
            else if(weekItems[0].max > 35 && weekItems[1].max > 35 && weekItems[2].max > 35)
                return {type:"highTemp", color: "yellow", title: "高温黄色预警"};
            // 是否低温
            if(Math.max(...dayItemsSet[0].map(v => {return v.temp})) <= 0 
                && dayItemsSet[0][0].temp > 16)
                return {type:"lowTemp", color: "red", title: "低温红色预警"};
            else if(Math.max(...dayItemsSet[0].map(v => {return v.temp})) <= 0 
                && dayItemsSet[0][0].temp > 12)
                return {type:"lowTemp", color: "orange", title: "低温橙色预警"};
            else if(Math.max(...dayItemsSet[0].map(v => {return v.temp})) <= 4 
                && dayItemsSet[0][0].temp > 14)
                return {type:"lowTemp", color: "yellow", title: "低温黄色预警"};    
            return null;
        });

        // 颜色主题
        const colorTheme = computed(() => {
            if(new Date().getTime() - sunriseTime.value.getTime() < 0 
                || sunsetTime.value.getTime() - new Date().getTime() < 0)
                return ["#151276", "#7939e0", "#332396", "#814ca7"];
            else if(new Date().getTime() - sunriseTime.value.getTime() < 3600000)
                return ["#49417b", "#f1b655", "#b1785b", "#d99877"];
            else if(sunsetTime.value.getTime() - new Date().getTime() < 3600000)
                return ["#9e2e2e", "#f59b0b", "#c15334", "#ff7361"];
            else 
                return ["#0273D7", "#76BAFF", "#388FFF", "#75C6FE"];
        })

        // 背景样式 
        const backgroundStyle = computed(() => {
            const styleObject = {
                'background-image': 'linear-gradient(132deg, '+ colorTheme.value[0] +' 0%, ' + colorTheme.value[1] + ' 100%)'
            } as Record<string, any>;
            return styleObject;
        });

        // 主页样式
        const weatherContainerStyle = computed(() => {
            const styleObject = {
                'border-bottom-left-radius': isShowDetail.value ? '0px' : null,
                'border-bottom-right-radius': isShowDetail.value ? '0px' : null
            } as Record<string, any>;
            return styleObject;
        });

        // 详细信息页面样式
        const detailContainerStyle = computed(() => {
            const styleObject = {
                'display': isShowDetail.value ? 'block' : 'none'
            } as Record<string, any>;
            return styleObject;
        })

        // 天气预报页面样式
        const reportContainerStyle = computed(() => {
            const styleObject = {
                'display': isShowReport.value ? 'block' : 'none'
            } as Record<string, any>;
            return styleObject;
        })

        // 其它参数页面样式
        const proindexContainerStyle = computed(() => {
            const styleObject = {
                'display': !isShowReport.value ? 'block' : 'none'
            } as Record<string, any>;
            return styleObject;
        })

        // 提交城市选择按钮样式
        const submitButtonStyle = computed(() => {
            const styleObject = {
                'background-color': colorTheme.value[2]
            } as Record<string, any>;
            return styleObject;
        })
        
        // 预警提示样式
        const iconStyle = computed(() => {
            const styleObject = {
                'animation-name': 'icon',
                'animation-duration': '0.8s',
                'animation-iteration-count': 'infinite'
            } as Record<string, any>;
            return styleObject;            
        })

        // 天气预报按钮样式
        const reportButtonStyle = computed(() => {
            const styleObject = {
                'background-color': isShowReport.value ? colorTheme.value[2] : "",
                'color': isShowReport.value ? 'white' : ""
            } as Record<string, any>;
            return styleObject;
        })

        // 其它参数按钮样式
        const proindexButtonStyle = computed(() => {
            const styleObject = {
                'background-color': !isShowReport.value ? colorTheme.value[2] : "",
                'color': !isShowReport.value ? 'white' : ""
            } as Record<string, any>;
            return styleObject;
        })

        // 显示（隐藏）详细信息
        function showDetail(){
            isShowDetail.value = !isShowDetail.value
        }

        // 显示（隐藏）城市选择
        function showSelectCity(){
            isShowSelectCity.value = !isShowSelectCity.value;
            selectedProvinceId.value = 0;
        }

        // 切换省份
        function switchProvince(){
            const selectedProvince = document.getElementById("provinceSelect") as any;
            selectedProvinceId.value = selectedProvince.selectedIndex;
        }

        // 提交城市选择
        function submitCity(){
            const selectedProvince = document.getElementById("provinceSelect") as any;
            const selectedCity = document.getElementById("citySelect") as any;
            currentProvinceId.value = selectedProvince.selectedIndex;
            currentCityId.value = selectedCity.selectedIndex;
            fetchData();
            resetCharts();
            isShowSelectCity.value = false;
            selectedProvinceId.value = 0;
        }

        // 显示天气预报
        function showReport(){
            isShowReport.value = true;
        }

        // 显示其它参数
        function showProindex(){
            isShowReport.value = false; 
        }

        // 24h天气预报滚动左键
        function scrollLeft(){
            const weatherBoardWidth = elementRef.value.getBoundingClientRect().width;
            const add = weatherBoardWidth - 120;
            const content = document.getElementById("f-weather-24h-content");
            if(content)
                if(content.offsetLeft + add > -32)
                    content.style.marginLeft = -32 + "px";
                else
                    content.style.marginLeft = content.offsetLeft + add + "px";
        }

        // 24h天气预报滚动右键
        function scrollRight(){
            const weatherBoardWidth = elementRef.value.getBoundingClientRect().width;
            const add = weatherBoardWidth - 120;
            const content = document.getElementById("f-weather-24h-content");
            if(content){
                const max = content.scrollWidth - weatherBoardWidth - 130;
                if(content.offsetLeft - add < -max)
                    content.style.marginLeft = "-" + max + "px";
                else
                    content.style.marginLeft = content.offsetLeft - add + "px";
            }
        }

        // 切换日期
        function switchDay(id: number){
            currentDayId.value = id;
        }

        // 左补0
        function addZero(n: number){
            return n < 10 ? "0" + n : n;
        }

        // 显示时间
        function showTime(dayIndex: number, hourIndex: number){
            if(dayIndex == 0){
                const time = new Date();
                if(hourIndex == 0)
                    return "现在";
                else{
                    return addZero((time.getHours() + hourIndex) % 24);
                }                
            }else{
                return addZero(hourIndex);
            }
        }

        // 显示标题
        function showTitle(index: number){
            switch (index) {
                case 0:
                    return "今天";
                case 1:
                    return "明天";
                default:
                    const day = new Date(new Date().getTime() + 24 * 60 * 60 * 1000 * index).getDay();
                    let str = "周";
                    switch (day) {
                        case 0:
                            return str + "日";
                        case 1:
                            return str + "一";
                        case 2:
                            return str + "二";
                        case 3:
                            return str + "三";
                        case 4:
                            return str + "四";
                        case 5:
                            return str + "五";
                        case 6:
                            return str + "六";
                    }
                    break;
            }
        }

        // 显示日期
        function showDate(index: number){
            const time = new Date(new Date().getTime() + 24 * 60 * 60 * 1000 * index);
            return addZero(time.getMonth() + 1) + "/" + addZero(time.getDate());
        }

        // 初始化图表
        function renderSunsetChart() {
            chartSunset.value = echarts.init(document.getElementById("sunset"), null, {
                height: 170,
                width: 380
            });
            chartSunset.value.setOption({
                series: [{
                    type: 'pie',
                    center: ["50%", "100%"],
                    radius: ["200%", "190%"],
                    startAngle: 180,
                    endAngle: 360,
                    label: {
                        show: false
                    },
                    emphasis: {
                        scale: false
                    },
                    emptyCircleStyle: {
                        borderType: 'dashed',
                    },
                }, {
                    type: "gauge",
                    center: ["50%", "100%"],
                    radius: "220%",
                    startAngle: 180,
                    endAngle: 360,
                    axisTick: {
                    show: false,
                    },
                    axisLabel: {
                    show: false,
                    },
                    splitNumber: 20,
                    axisLine: {
                    show: false
                    },
                    splitLine: {
                    length: 3,
                    lineStyle: {
                        width: 10,
                        color: 'white'
                    }
                    }
                }]
            })
        }

        function render24hChart() {
            chart24h.value = echarts.init(document.getElementById("chart24h"), null, {
                width: 1885,
                height: 75
            });
            chart24h.value.setOption({
                xAxis: {
                    type: 'category',
                    show: false
                },
                yAxis: {
                    type: 'value',
                    show: false
                },
                series: [{
                    type: 'line',
                    itemStyle: {
                        color: 'white'
                    }
                }]
            });
        }

        function render7dChart() {
            const weatherBoardWidth = elementRef.value.getBoundingClientRect().width;
            const chart7dWidth = Math.max(weatherBoardWidth, 400) * 1.11;
            chart7d.value = echarts.init(document.getElementById("chart7d"), null, {
                width: chart7dWidth,
                height: 90
            });
            chart7d.value.setOption({
                grid: {
                    left: 0
                },
                xAxis: {
                    type: 'category',
                    show: false
                },
                yAxis: {
                    type: 'value',
                    show: false
                },
                series: [{
                    type: 'line',
                    itemStyle: {
                        color: '#5C90F9'
                    }
                },{
                    type: 'line',
                    itemStyle: {
                        color: '#FC9657'
                    }
                }]
            });
        }

        // 组件宽度改变
        function onWeatherBoradResize() {
            const weatherBoardWidth = elementRef.value.getBoundingClientRect().width;
            // 7d预报
            const chart7dWidth = Math.max(weatherBoardWidth, 400) * 1.11;
            // chart7d.value?.resize();
           
            // 空气质量点
            const airPoint = document.getElementById("airPoint");
            const maxWidth = Math.max(elementRef.value.getBoundingClientRect().width, 400);
            if(airPoint)
                airPoint.style.marginLeft = (air.value / 500 * (maxWidth - 50) - 5) + "px";
            
            // 24hscroll
            const content = document.getElementById("f-weather-24h-content");
            if(content){
                const max = content.scrollWidth - weatherBoardWidth - 130;
                if(content.offsetLeft < -max)
                    content.style.marginLeft = "-" + Math.max(max, 32) + "px";
            }
        }

        // 刷新图表
        function resetAirProgress(){
            const airPoint = document.getElementById("airPoint");
            if(airPoint)
                airPoint.style.marginLeft = 
                    (air.value / 500 * (elementRef.value.getBoundingClientRect().width -50) - 5) + "px";
        }

        function resetChartSunset(){
            if(chartSunset.value)
                chartSunset.value.setOption({
                    series: [{
                        data: [{
                            value: new Date().getTime() - sunriseTime.value.getTime(),
                            itemStyle: {
                                borderRadius: 10,
                                color: {
                                    type: 'linear',
                                    x: 1,
                                    y: 0,
                                    x2: 0,
                                    y2: 0,
                                    colorStops: [{
                                        offset: 1, color: colorTheme.value ? colorTheme.value[3] : 'white'
                                    }, {
                                        offset: 0, color: 'white'
                            }]}}
                        }, {
                            value: sunsetTime.value.getTime() - new Date().getTime(),
                            itemStyle: {
                                opacity: 0,
                            }
                        }]
                    }]
                });
        }

        function resetChart24h(){
            if(chart24h.value)
                chart24h.value.setOption({
                    series: [{
                        data: dayItemsSet[currentDayId.value].map(v => {return v.temp}),
                        type: 'line'
                    }]
                });
        }

        function resetChart7d(){
            if(chart7d.value)
                chart7d.value.setOption({
                    series: [{
                        data: weekItems.map(v => {return v.min}),
                    },{
                        data: weekItems.map(v => {return v.max}),
                    }]
                });
        }
        
        function resetCharts(){
            resetAirProgress();
            resetChartSunset();
            resetChart24h();
            resetChart7d();
        }

        // 调用api获取数据
        function fetchData(){
            // 返回气温、天气、日出日落、空气质量、建议
            const urlqq = "https://wis.qq.com/weather/common?source=pc&weather_type=observe|forecast_1h|forecast_24h|index|rise|air"
                + "&province=" + cityItems[currentProvinceId.value].province
                + "&city=" + cityItems[currentProvinceId.value].city[currentCityId.value];
            jsonp(urlqq, (err, data) => {
                if (err) {
                    console.error('Error fetching data:', err);
                } else {
                    const info = data.data;
                    temperature.value = info.observe.degree;
                    max.value = info.forecast_24h[1].max_degree;
                    min.value = info.forecast_24h[1].min_degree;
                    weather.value = info.observe.weather;
                    air.value = info.air.aqi;
                    sunriseTime.value = new Date();
                    sunsetTime.value = new Date();
                    sunriseTime.value.setHours((Number)(info.rise[0].sunrise.split(":")[0]));
                    sunriseTime.value.setMinutes((Number)(info.rise[0].sunrise.split(":")[1]));
                    sunriseTime.value.setSeconds(0);
                    sunriseTime.value.setMilliseconds(0);
                    sunsetTime.value.setHours((Number)(info.rise[0].sunset.split(":")[0]));
                    sunsetTime.value.setMinutes((Number)(info.rise[0].sunset.split(":")[1]));
                    sunriseTime.value.setSeconds(0);
                    sunriseTime.value.setMilliseconds(0);
                    adviceItems.forEach(advice => {
                        advice.value = info.index[advice.key];
                    })
                    proindexItemsSet[0][0].value = info.index.ultraviolet.info;
                    proindexItemsSet[0][1].value = info.observe.precipitation + "mm";
                    let i;
                    for(i = 1; i < 8; i++){
                        weekItems[i-1].icon = info.forecast_24h[i].day_weather_code;
                        weekItems[i-1].max = info.forecast_24h[i].max_degree;
                        weekItems[i-1].min = info.forecast_24h[i].min_degree;
                    }
                    for(i = 0; i < 24; i++){
                        dayItemsSet[0][i].icon = info.forecast_1h[i].weather_code;
                        dayItemsSet[0][i].temp = info.forecast_1h[i].degree;
                    }
                    for(i = 0; i < 48; i++){
                        if(info.forecast_1h[i].update_time.endsWith("000000") && i != 0)
                            break;
                    }
                    i--;
                    for(let j = 0; j < 24; i++, j++){
                        dayItemsSet[1][j].icon = info.forecast_1h[i].weather_code;
                        dayItemsSet[1][j].temp = info.forecast_1h[i].degree;
                    }
                    resetCharts();
                }
            });
            
            // 返回其它参数
            const headers = new Headers();
            headers.append('User-Agent', 'Win64');
            const str = "location=" + cityItems[currentProvinceId.value].city[currentCityId.value]
                        + "&public_key=P2yFGyRckTUNG9rFt"
                        + "&ts=" + new Date().getTime()
                        + "&ttl=3000";
            const key = "Sh3s--_vh1BWqUb_w";
            const result = CryptoJS.HmacSHA1(str, key);
            const sig = encodeURIComponent(result.toString(CryptoJS.enc.Base64));
            const urlxz = "https://api.seniverse.com/v3/weather/now.json?" + str + "&sig=" + sig;
            fetch(urlxz, {
                method: 'GET',
                headers,
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    const info = data.results[0].now;
                    proindexItemsSet[1][0].value = info.humidity + "%";
                    proindexItemsSet[1][1].value = info.feels_like + "°";
                    proindexItemsSet[2][0].value = info.pressure + "mpa";
                    proindexItemsSet[2][1].value = Math.round((Number)(info.visibility)) + "km";
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                });
            resetCharts();
        }

        // 当前选择的日期改变
        watch(currentDayId, ()=>{
            const content24 = document.getElementById("f-weather-24h-content") as any;
            content24.style.marginLeft = -32 + "px";
            resetChart24h();
        })

        onMounted(() => {
            useResizeObserver(elementRef.value, onWeatherBoradResize);
            renderSunsetChart();
            render24hChart();
            render7dChart();
            fetchData();
        })

        return () => {
            return (
                <div>
                    <div ref={elementRef} class="f-weather-background" style={backgroundStyle.value}>
                        {/* 主页面 */}
                        <div class="f-weather-container" style={weatherContainerStyle.value}>
                            {/* header */}
                            <div class="f-weather-header">
                                {/* 城市 */}
                                <div class="f-weather-city">
                                    {/* 显示城市 */}
                                    <span class="f-weather-city-title">{cityItems[currentProvinceId.value].city[currentCityId.value] + "市"}</span>
                                    {/* 下拉选择城市 */}
                                    <img src="/components/weather/src/image/choose.png"
                                        class="f-weather-city-icon"
                                        onClick={showSelectCity}/>
                                    {isShowSelectCity.value ? 
                                        <div class="f-weather-city-select">
                                            <select id="provinceSelect" onChange={switchProvince}>
                                                {cityItems.map((provinceItem) => {
                                                    return <option>{provinceItem.province}</option>
                                                })}
                                            </select>
                                            <select id="citySelect">
                                                {cityItems[selectedProvinceId.value].city.map((cityItem) => {
                                                    return <option>{cityItem}</option>
                                                })}
                                            </select>
                                            <button class="f-weather-button f-weather-button-city" style={submitButtonStyle.value} 
                                                onClick={submitCity}>确定</button>
                                        </div> 
                                        : ""
                                    }
                                </div>
                                {/* 显示隐藏详细信息 */}
                                <button class="f-weather-button f-weather-button-detail" onClick={showDetail}>
                                    {isShowDetail.value ? <div>隐藏详细信息</div>: <div>显示详细信息</div>}
                                </button>
                            </div>
                            {/* 日出日落进度条 */}
                            <div id="sunset" class="f-weather-sunset-progress"></div>
                            <div class="f-weather-sunset-container">
                                <img src="/components/weather/src/image/sunrise.png" 
                                    class="f-weather-sunrise-img"/>
                                <img src="/components/weather/src/image/sunset.png" 
                                    class="f-weather-sunset-img"/>
                                <div>
                                    <span class="f-weather-sunrise-text">
                                        {addZero(sunriseTime.value.getHours()) + ":" + addZero(sunriseTime.value.getMinutes())}</span>
                                    <span class="f-weather-sunset-text">
                                        {addZero(sunsetTime.value.getHours()) + ":" + addZero(sunsetTime.value.getMinutes())}</span>
                                </div>                                    
                            </div>
                            {/* 主要数值信息 */}
                            <div class="f-weather-information-container">
                                {/* 温度天气与预警 */}
                                <div class="f-weather-information">
                                    <div class="f-weather-information-row1">
                                        {/* 温度 */}
                                        <span class="f-weather-temperature">{temperature.value + " °"}</span>
                                        {/* 天气 */}
                                        <span class="f-weather-weather">{weather.value}</span>
                                    </div>
                                    <div class="f-weather-information-row2">
                                        {/* 预警 */}
                                        {warning.value ?
                                            <span class="f-weather-warning-container">
                                                <span class="f-weather-warning">
                                                    <img src={"/components/weather/src/image/warningImage/"
                                                        + (warning.value.type + "-" + warning.value.color) + ".png"}
                                                        class="f-weather-warning-icon"
                                                        style={warning.value ? iconStyle.value : ""} />
                                                    <span class="f-weather-warning-text"> {warning.value.title}</span>
                                                </span>
                                            </span>
                                            : ""}
                                    </div>
                                </div>
                                {/* 最高最低温 */}
                                <div class="f-weather-information-text f-weather-maxmin">{min.value + "° ~ " + max.value + "°"}</div>
                                {/* 建议 */}
                                <div class="f-weather-information-text f-weather-advice-container">
                                    {adviceItems.map((adviceItem) => {
                                        return themeItems[theme.value].adviceItems.includes(adviceItem.key) ? 
                                            <span class="f-weather-advice">
                                                <span>{adviceItem.value.name}：{adviceItem.value.info}</span>
                                                {themeItems[theme.value].adviceItems.indexOf(adviceItem.key) != 2 ? <span class="f-weather-advice-line"></span> : ""}
                                                <span class="f-weather-advice-text">{adviceItem.value.detail}</span>
                                            </span>
                                        : ""
                                    })}
                                </div>
                                {/* 空气质量进度条 */}
                                <div class="f-weather-air">
                                    <div class="f-weather-air-title">空气质量：{air.value + " - " + airLevel.value}</div>
                                    <div class="f-weather-air-progress">
                                        <f-progress percent={100} enableBackgroundImg={true} 
                                            backgroundImg="linear-gradient(90deg, #01C84C 0%, #F7FF01 26%, #FF0000 53%, #800080 78%, #A52A2A 100%)"></f-progress>
                                        <img src="/components/weather/src/image/point.png" id="airPoint"
                                            class="f-weather-air-point"/>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {/* 详细信息 */}
                        <div class="f-weather-container f-weather-detail" style={detailContainerStyle.value}>
                            {/* 切换页面*/}
                            <div style="display:flex">
                                <button class="f-weather-button f-weather-button-report" style={reportButtonStyle.value} onClick={showReport}>
                                    天气预报</button>
                                <button class="f-weather-button f-weather-button-proindex" style={proindexButtonStyle.value} onClick={showProindex}>
                                    其它参数</button>
                            </div>
                            {/* 天气预报 */}
                            <div style={reportContainerStyle.value}>
                                {/* 24h预报 */}
                                <div class="f-weather-24h-container">
                                    <div class="f-weather-24h-title">24小时天气预报</div>
                                    {/* 左右按钮 */}
                                    <div class="f-weather-lrbutton-container">
                                        <img src="/components/weather/src/image/arrow-left.png" class="f-weather-lrbutton-l"
                                            onClick={scrollLeft}/>
                                        <img src="/components/weather/src/image/arrow-right.png"  class="f-weather-lrbutton-r"
                                            onClick={scrollRight}/>
                                    </div>
                                    {/* 24h预报 */}
                                    <div class="f-weather-24h-content-scroll">
                                        <div id="f-weather-24h-content">
                                            {dayItemsSet.map((dayItems, dayIndex) => {
                                                return ((dayIndex) == currentDayId.value) ? 
                                                    <div>
                                                        <tr id={"report" + dayIndex} class="f-weather-24h-tr">
                                                            {dayItems.map((dayItem, hourIndex) => {
                                                                return <td class="f-weather-24h-td">
                                                                    <div>{showTime(dayIndex, hourIndex)}</div>
                                                                    <img src={"http://mat1.gtimg.com/pingjs/ext2020/weather/pc/icon/weather/day/" + dayItem.icon + ".png"} 
                                                                        class="f-weather-24h-img"></img>
                                                                    <div>{dayItem.temp + "°"}</div>
                                                                    </td>
                                                            })}
                                                        </tr>
                                                    </div>
                                                : ""
                                            })}
                                            <div id="chart24h" class="f-weather-chart24h"></div>
                                        </div>
                                    </div>
                                </div>
                                {/* 7d预报 */}
                                <div class="f-weather-7d-container">
                                    <div class="f-weather-7d-title">七日天气预报</div>
                                    <tr class="f-weather-7d-tr">
                                        {weekItems.map((weekItem, index) => {
                                            return <td id={"day" + index} class="f-weather-7d-td"
                                                style={"background-color: " + (index == currentDayId.value ? "rgba(0, 0, 0, 0.05)" : "none")}
                                                onClick={() => switchDay(index)}>
                                                <div class="f-weather-7d-td-title">{showTitle(index)}</div>
                                                <div class="f-weather-7d-td-date">{showDate(index)}</div>
                                                <img src={"http://mat1.gtimg.com/pingjs/ext2020/weather/pc/icon/weather/day/" + weekItem.icon+ ".png"}
                                                    class="f-weather-7d-td-img"/>
                                                <div class="f-weather-7d-td-margin">{weekItem.max + "°"}</div>
                                                <div>{weekItem.min + "°"}</div>
                                            </td>
                                        })}
                                    </tr>
                                    <div id="chart7d" class="f-weather-chart7d"></div>
                                </div>
                            </div>
                            {/* 其他参数 */}
                            <div style={proindexContainerStyle.value}>
                                {proindexItemsSet.map((proindexItems) => {
                                    return <tr class="f-weather-proindex-tr">
                                        {proindexItems.map((proindexItem) => {
                                            return <td class="f-weather-proindex-td">
                                                <div class="f-weather-proindex-content-scroll">  
                                                    <div class="f-weather-proindex-content">
                                                        <img src={"/components/weather/src/image/proindexImage/" + proindexItem.icon + ".png"} 
                                                            class="f-weather-proindex-icon"/>
                                                        <div class="f-weather-proindex-text">
                                                            <div class="f-weather-proindex-title">{proindexItem.title}</div>
                                                            <div class="f-weather-proindex-value">{proindexItem.value}</div>
                                                        </div>
                                                        <div class="f-weather-proindex-line"></div>
                                                        <br/>
                                                        <div class="f-weather-proindex-info">{proindexItem.info}</div>
                                                        <br/>
                                                        <div>{proindexItem.explain}</div>
                                                    </div>
                                                </div>
                                            </td>
                                        })}
                                    </tr>
                                })}
                            </div>
                        </div>
                    </div>
                </div>
            );
        };
    }
});